package com.indictor.bean;


import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


public class IndicatorCommandComputer implements IndicatorComputer {

    public BigDecimal compute(IndicatorCommand indicatorCommand, int precent, int mode, Map<String, BigDecimal> map) {
        List<Indicator> indicators = indicatorCommand.getIndicators();
        IndicatorApplicationContext instance = IndicatorApplicationContext.getInstance();
        IndicatorCalculator indicatorCalculator = new DefaultIndicatorCalculator();
        for (Indicator indicator : indicators) {
            IndicatorCommand command = instance.get(indicator.getKey());
            if (command != null) {
                List<Indicator> commandIndicators = command.getIndicators();
                int size = commandIndicators.size();
                IndicatorCalculator subindicatorCalculator = new DefaultIndicatorCalculator();
                for (int i = 0; i < size; i++) {
                    Indicator indicator1 = commandIndicators.get(i);
                    subindicatorCalculator.calculate(indicator1, getValue(indicator1, map));
                }
                indicatorCalculator.calculate(indicator, subindicatorCalculator.getValue());
                subindicatorCalculator = null;
            } else {
                indicatorCalculator.calculate(indicator, getValue(indicator, map));
            }
        }
        return indicatorCalculator.getValue();
    }


    private BigDecimal getValue(Indicator indicator, Map<String, BigDecimal> map) {
        BigDecimal bigDecimal = map.get(indicator.getKey());
        if (bigDecimal == null) {
            bigDecimal = indicator.getValue();
        }
        return bigDecimal;
    }


}
